package com.sgj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.enums.RespBeanEnum;
import com.sgj.exception.GlobalException;
import com.sgj.mapper.UserMapper;
import com.sgj.pojo.User;
import com.sgj.service.IUserService;
import com.sgj.utils.CookieUtil;
import com.sgj.utils.MD5Util;
import com.sgj.utils.UUIDUtil;
import com.sgj.vo.LoginVo;
import com.sgj.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 沈国纪
 * @since 2021-01-13
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        // 获取手机号
        String mobile = loginVo.getMobile();
        // 获取密码
        String password = loginVo.getPassword();

        // 根据手机号查询用户
        User user = userMapper.selectById(mobile);
        if (null == user) {
            throw new GlobalException(RespBeanEnum.PHONE_ERROR);
        }
        // 判断加密后的密码是否与数据库一致
        if (!MD5Util.fromPassToDBPass(password, user.getSalt()).equals(user.getPassword())) {
            throw new GlobalException(RespBeanEnum.PASSWORD_ERROR);
        }
        // 生产 cookie
        String ticket = UUIDUtil.uuid();
        // 将用户信息存入 reids 中
        redisTemplate.opsForValue().set("user:" + ticket, user);
        CookieUtil.setCookie(request, response, "userTicket" ,ticket);
        return RespBean.success();
    }

    /**
     * 根据 cookie 获取用户
     * @param userTicket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        // 如果 userTicket 为空，则返回空
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        // 通过 reids 获取用户信息
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        if (user != null) {
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }
        return user;
    }
}
